package org.ybxb.demo.user.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.ybxb.demo.user.entity.User;
import org.ybxb.demo.user.service.IUserService;
import org.ybxb.demo.user.vo.UserVo;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @ProjectName: maven-boot-demo
 * @PackageName: org.ybxb.demo.controller
 * @Description:
 * @Author: hy.bai
 * @Date: 2025-07-01 14:23
 */
@RestController
@RequestMapping("/api/user")
public class UserController {


    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Resource
    private IUserService userService;

    /**
     * 根据ID查询用户
     */
    @GetMapping("/findById/{id}")
    public User findUserById(@PathVariable(value = "id") String id) {
        User userFromDb = userService.getById(id);
        if (Objects.equals("10", id)) {
            throw new RuntimeException("模拟异常...");
        }
        return userFromDb;
    }

    /**
     * 查询列表
     */
    @GetMapping("/queryList")
    public List<User> queryList() {
        List<User> resultList = userService.list();
        log.info("===============查询用户列表===============");
        return resultList;
    }


    /**
     * 新增
     */
    @PostMapping("/save")
    public String save(@RequestBody UserVo userVo) {
        User userDb = new User();
        BeanUtils.copyProperties(userVo, userDb, User.class);
        userDb.setCreateTime(LocalDateTime.now());
        userDb.setUpdateTime(LocalDateTime.now());
        log.info("新增的用户数据:{}", userDb);
        return userService.save(userDb) ? "新增成功" : "新增失败";
    }


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        String filename = file.getOriginalFilename();
        long fileSize = file.getSize();
        String result = MessageFormat.format("文件名是: {0}, 文件大小是: {1}, 单位:KB", filename, fileSize / 1000);
        log.info(result);
        return result;
    }


    /**
     * 文件下载
     *
     * @param response
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        File file = new File("E:\\systemFile\\admin\\Downloads\\Linux入门到精通1500页电子版教程v2.pdf");
        // 读到流中
        InputStream inputStream = new FileInputStream(file);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = file.getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        // 向响应头中设置文件大小
        response.addHeader("Content-Length", String.valueOf(Files.size(Path.of(file.getPath()))));
        OutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        // 从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }
}
